package com.yh.util;


import java.io.File;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;



import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.yh.bean.FileSet;
import com.yh.service.ManageService;
@Component
public class FileUtil {

	@SuppressWarnings("unused")
	public static boolean uploadFile(MultipartFile file,HttpServletRequest request){
		//1.获取控制层传过来的 file 类型文件
		String image =DateUtil.getCurrentDate()+file.getOriginalFilename();
		System.out.println(image+"***********************");
		//2.把照片保存到本地文件夹
		//2.1获取本地文件夹地址
		String path = request.getServletContext().getRealPath("/photos")+"/"+image;
		long scope = file.getSize();

		boolean result = FileUtil.checkFile(scope,image);
		if(result){
			//3.创建文件对象
			File newFile = new File(path);
			//4.执行上传动作
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return true;
			
			
		}else {
			
			
			return false;
		}
		
	}

	@Autowired
	private ManageService service;	
	private static FileUtil util;
	@PostConstruct
    public void init() {    
        util = this;
        util.service=this.service;
    } 	
	public static boolean checkFile(long scope,String photoName){		
		FileSet fileSet=util.service.queryFileSet();		
		int size= fileSet.getFileset_maxsize();//查到的size
		String filetype=fileSet.getFileset_type();//查到的类型
		System.out.println(photoName);
		photoName=photoName.substring(photoName.lastIndexOf(".")+1);
		String photoName1=photoName.substring("dsfjd.jpg".lastIndexOf("\\.")+1);
		System.out.println(photoName1+"******************************");
		System.out.println("工具类的======================="+photoName);
		System.out.println("==============================="+scope);
		String[] Array = filetype.split("\\.");
		if(size>scope/(1024*1024)){
			for(int i=0;i<Array.length;i++){
				if(Array[i].equals(photoName)){
						return true;
					}
				}
		}
		
		return false;
	}



}
